import axios from 'axios'
import {
  Message
} from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 0) {
      if (response.config.alert) {
        Message({
          message: res.msg || "服务器错误，请稍后再试",
          type: 'error',
          duration: 2000
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: '服务器错误，请稍后再试',
      type: 'error',
      duration: 2000
    })
    return Promise.reject(error)
  }
)

export default service